#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 2e5 + 5;

int n, m;
map<string, string> mp;
struct cmp {
  bool operator()(const string& s1, const string& s2) const {
    string a1 = mp[s1], a2 = mp[s2];
    if (a1 != a2) return a1 < a2;
    return s1 < s2;
  }
};
set<string, cmp> lib;
set<string, cmp> ret;

void back() {
  for (string book : ret) {
    lib.insert(book);
    auto it = lib.find(book);
    if (it == lib.begin())
      cout << "Put " << book << " first" << endl;
    else {
      it = prev(it);
      cout << "Put " << book << " after " << *it << endl;
    }
  }
  cout << "END" << endl;
  ret.clear();
}
void parse(string line, string& book, string& author) {
  int p1 = line.find('\"');
  int p2 = line.find('\"', p1 + 1);
  book = line.substr(p1, p2 + 1 - p1);
  int p3 = p2 + 5;
  author = line.substr(p3);
}
void parse2(string line, string& cmd, string& book) {
  cmd = line.substr(0, 6);
  if (cmd == "SHELVE") return;
  book = line.substr(7);
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  // freopen("1.txt", "r", stdin);
  // freopen("2.txt", "w", stdout);
  string line;
  while (getline(cin, line) && line != "END") {
    string book, author;
    parse(line, book, author);
    mp[book] = author;
    lib.insert(book);
  }
  while (getline(cin, line) && line != "END") {
    string cmd, book;
    parse2(line, cmd, book);
    if (cmd == "BORROW")
      lib.erase(book);
    else if (cmd == "RETURN")
      ret.insert(book);
    else
      back();
  }
  return 0;
}